﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Drawing.Text;
using System.Runtime.InteropServices;

namespace Walson.Drawing
{
    class ResourceFont
    {
        private  Stream fontStream;
        private  byte[] fontdata;
        private  GCHandle hObject;
        private  IntPtr pFontData;
        private  PrivateFontCollection pfc;

        public ResourceFont()
        {

        }

        /// <summary>
        /// 从指定文件加载字体
        /// </summary>
        /// <param name="fontFineName">字体文件名</param>
        /// <returns>字体</returns>
        public Font GetFontFromFile(string fontFineName)
        {
            System.Drawing.Text.PrivateFontCollection colFont = new System.Drawing.Text.PrivateFontCollection();
            colFont.AddFontFile(fontFineName);
            Font f = new System.Drawing.Font(colFont.Families[0], 24, FontStyle.Regular, GraphicsUnit.Point);
            return f;
        }

        /// <summary>
        /// 获取嵌入的字体
        /// </summary>
        /// <param name="name">程序集的简单名字。可采用如下方法获取：String projectName = Assembly.GetExecutingAssembly().GetName().Name.ToString();</param>
        /// <param name="fontName">字体名称。该字体应当位于 name\Resources 文件夹下。</param>
        /// <returns></returns>
        public FontFamily GetEmbeddedFont(string name,string fontName)
        {
            pfc = new PrivateFontCollection(); //
            //加载自定义的字体  
            String projectName = name;
            fontStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(name + ".Resources." + fontName);
            string[] strs=System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
            foreach (string str in strs)
            {
                str.Remove(0);
            }
            fontdata = new byte[fontStream.Length];
            fontStream.Read(fontdata, 0, (int)fontStream.Length);
            fontStream.Close();


            hObject = GCHandle.Alloc(fontdata, GCHandleType.Pinned);

            pFontData = hObject.AddrOfPinnedObject();
            pfc.AddMemoryFont(pFontData, fontdata.Length);

            return pfc.Families[0];
        }
    }
}
